//
//  YDOneRechargeViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2017/12/19.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDOneRechargeViewController.h"
#import "YDRechargeTopView.h"
#import "YDRechargeWithdrawalButtonView.h"
#import "YDChoosePayTypeCell.h"
#import "YDChoosePayTypeFooterView.h"
#import "YDRechargeController.h"
#import "YDRechargeBankListModel.h"
#import "YDAdvertViewController.h"
#import "OttoKeyboardView.h"

#import "YDRechargeSuccessViewController.h"

@interface YDOneRechargeViewController ()<SYRechargeWithdrawalButtonViewDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,TextFieldClickReturnDelegate>



//顶部显示余额
@property (nonatomic , weak) YDRechargeTopView *topView;
//金额
@property (nonatomic , weak) UIView *accountContentView;
//金额label
@property (nonatomic , weak) UILabel *accountLabel;
//金额输入框
@property (nonatomic , weak) OttoTextField *accountTextField;



@property (nonatomic, strong) UITableView *tableView;


//充值按钮
@property (nonatomic , weak) YDRechargeWithdrawalButtonView *buttonView;
@property (nonatomic, strong)NSMutableArray *dataList;


/**
 充值银行卡列表
 */
@property (nonatomic , strong) NSMutableArray *bankListModelArray;

@property (nonatomic , strong) YDRechargeBankListModel *selectedModel;

@end

@implementation YDOneRechargeViewController

-(NSMutableArray *)bankListModelArray
{
    if (_bankListModelArray == nil) {
        _bankListModelArray = [NSMutableArray array];
    }
    return _bankListModelArray;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"充值";
    [self.navigationController.navigationBar setHidden:YES];
    [self dismissKeyBoard];
    [self topView];
    [self addTextField];
    [self tableView];
    [self buttonView];
}


/**
 处理模型，开始默认第一个选中，之后传递index
 */
-(void)resloveRechargeBankListModelWithIndexPath:(NSIndexPath *)indexPath
{
    if (self.bankListModelArray.count == 0)return;
    for (YDRechargeBankListModel *model in self.bankListModelArray) {
        model.isSelected = NO;
    }
    
    YDRechargeBankListModel *model = self.bankListModelArray[indexPath.row];
    model.isSelected = YES;
    self.selectedModel = model;
    
}
#pragma mark -UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField.text.length) {
        [self.buttonView enableButton];
    }else
    {
        [self.buttonView disableButton];
    }
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    
    if ([textField isFirstResponder]) {
        if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
            return NO;
        }
    }
    
    //只能输入一个小数点及小数点两位
    if ([string isEqualToString:@"."]) {
        if ([textField.text containsString:@"."]) {
            return NO;
        }else{
            return YES;
        }
    }
    
    if ([textField.text containsString:@"."]) {
        if (range.location > [textField.text rangeOfString:@"."].location + 2) {
            return NO;
        }
    }
    
    
    
    return YES;
}

#pragma mark - 点击充值
- (void)rechargeWithdrawalButtonViewButtonClick
{
    
    NSString *minTips;
    NSString *MaxTips;
    
    CGFloat minMoney;
    CGFloat maxMoney;
    
    if (self.payType == SYPayType_card) {
        minTips = @"请输入正确的金额，金额不能低于100元";
        MaxTips = @"单笔充值金额不超过50000元";
        minMoney = 100.f;
        maxMoney = 50000.f;
        
    }else if(self.payType == SYPayType_jd)
    {
        minTips = @"请输入正确的金额,金额不能低于5元";
        MaxTips = @"单笔充值金额不超过4500元";
        minMoney = 5.f;
        maxMoney = 4500.f;
    }else
    {
        minTips = @"请输入正确的金额,金额不能低于5元";
        MaxTips = @"单笔充值金额不超过2000元";
        minMoney = 5.f;
        maxMoney = 2000.f;
    }
    
    if(![NSString isFloatNumString:self.accountTextField.text] || [self.accountTextField.text floatValue] < minMoney)
    {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:minTips isExistNav:NO];
        return;
    }
    
    if (![NSString isFloatNumString:self.accountTextField.text] || [self.accountTextField.text floatValue] > maxMoney) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:MaxTips isExistNav:NO];
        return;
    }
    
    NSDictionary *dic = @{@"phone" : [[SYUserDataManger sharedInstance] getUerPhone],
                          @"amount"  :self.accountTextField.text,
                          };
    
    
    //    switch (self.payType) {
    //        case PZPayType_card:
    //        {
    //
    //            NSString *paramStr = [NSString urlPramsStrWithDic:dic];
    //
    //
    //            //http://10.0.0.48:8083
    //            NSString *url = [NSString stringWithFormat:@"%@%@?%@",baseUrlHttp,@"/quickpay/sdquickpay",paramStr];
    //
    //
    //            PZAdvertViewController *payVc = [[PZAdvertViewController alloc] init];
    //            payVc.urlStr = url;
    //            payVc.title = @"银联充值";
    //            payVc.money = self.accountTextField.text;
    //            [self.navigationController pushViewController:payVc animated:YES];
    //
    ////            quickbank
    //        }
    //            break;
    //        case PZPayType_jd:
    //        case PZPayType_qq:
    //        {
    RequestType requestType;
    
    switch (self.payType) {
        case SYPayType_card:
            requestType = GetCardPay;
            break;
        case SYPayType_qq:
            requestType = GetQQpay;
            break;
        case SYPayType_jd:
            requestType = GetJdPay;
            break;
            
        default:
            break;
    }
    
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:dic];
    [[SYProgressHUD sharedInstance] showMBHudWithString:kLoadingText SuperView:self.view];
    [BaseNetRequest sessionRequestWithparameters:params method:GETMethod requstType:requestType WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        DDLog(@"===%@" , resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            
            
            NSString *url = [resultDict objectForKey:@"result"][@"url"];
            
            if (self.payType == SYPayType_jd) {
                YDAdvertViewController *payVc = [[YDAdvertViewController alloc] init];
                payVc.urlStr = url;
                payVc.title = @"京东充值";
                payVc.isJD = YES;
                payVc.money = self.accountTextField.text;
                [self.navigationController pushViewController:payVc animated:YES];
            }
            else if (self.payType == SYPayType_card)
            {
                YDAdvertViewController *payVc = [[YDAdvertViewController alloc] init];
                payVc.urlStr = url;
                payVc.title = @"银联充值";
                payVc.money = self.accountTextField.text;
                [self.navigationController pushViewController:payVc animated:YES];
                
//                YDRechargeSuccessViewController *vc  = [[YDRechargeSuccessViewController alloc] init];
//                vc.hidesBottomBarWhenPushed = YES;
//                [self.navigationController pushViewController:vc animated:YES];
            }
            else
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            }
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:NO];
            
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"服务器异常，请稍后充值" isExistNav:NO];
    }];
    
    //
    //            break;
    //        }
    //
    //        default:
    //            break;
    //    }
    
    
    
    
    //    NSDictionary *dic = @{@"publisherId" : [[PZUserDataManger sharedInstance] getUser_Id],
    //                          @"paymentType" : @1,
    //                          @"amount"      : self.accountTextField.text,
    //                          @"bankCode"  : self.selectedModel.bankCode,
    //                          };
    
    //
    
    
    
}

- (void)alertWithMessage:(NSString *)message
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:message ButtonTitle:@"确定" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
        
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
    
}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.bankListModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDChoosePayTypeCell *cell = [YDChoosePayTypeCell cellWithTableView:tableView];
    //    cell.payDic = [self.dataList objectAtIndex:indexPath.row];
    
    YDRechargeBankListModel *model = self.bankListModelArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    YDChoosePayTypeFooterView *footer = [YDChoosePayTypeFooterView footerViewWithTableView:tableView];
    footer.payType = self.payType;
    return footer;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 250;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CGFloat leftGap =  rate375(17);
    CGFloat lblH = isPhoneX ? rateX812(50) : rate750(50);
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, lblH)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLbl = [UILabel new];
    [view addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(leftGap));
        make.top.right.equalTo(view);
        make.bottom.equalTo(view).offset(-1);
        
    }];
    titleLbl.textColor = [UIColor colorWithHexString:battleshipGrey];
    titleLbl.text = @"选择银行";
    
    
    UILabel *line = [UILabel new];
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@1);
        make.left.right.bottom.equalTo(view);
    }];
    // line.backgroundColor = [UIColor colorWithHexString:mainGray];
    
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.fillColor = nil;
    layer.strokeColor = [UIColor colorWithHexString:mainGray].CGColor;
    layer.lineWidth = 1;
    layer.lineDashPattern = @[@3,@2];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    
    CGPathAddLineToPoint(path, NULL, LKScreenW,0);
    layer.path = path;
    CGPathRelease(path);
    [line.layer addSublayer:layer];
    
    return view;
}

- (CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    //    return isPhoneX ? rateX812(50) : rate750(50);
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(41) : rate750(41);
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    self.payType = indexPath.row ? PZPayType_aliPay : PZPayType_card;
    //
    //    [self.dataList enumerateObjectsUsingBlock:^(NSMutableDictionary * obj, NSUInteger idx, BOOL * _Nonnull stop) {
    //
    //        if (idx == indexPath.row) {
    //            [obj setValue:@1 forKey:@"isSelected"];
    //
    //
    //        }else
    //        {
    //            [obj setValue:@0 forKey:@"isSelected"];
    //        }
    //    }];
    
    [self resloveRechargeBankListModelWithIndexPath:indexPath];
    
    
    [tableView reloadData];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSArray *subviews = [self.view subviews];
    for (UITextField *textField in subviews) {
        if (textField == self.accountTextField) {
            [self.accountTextField resignFirstResponder];
        }
    }
    
}


#pragma mark - TextFieldClickReturnDelegate
- (void)textFieldClickReturn:(OttoTextField *)textField{
    [textField resignFirstResponder];
    NSLog(@"return - %@",textField.text);
}

////*******PZRechargeTopView********////
-(YDRechargeTopView *)topView
{
    if (_topView == nil) {
        NSString *accountString = [[SYUserDataManger sharedInstance] getUserAccountNumberString];
        YDRechargeTopView *topView = [YDRechargeTopView rechargeTopViewWithAmount:accountString];
        __weak typeof(self)weself = self;
        NSString *title = nil;
        switch (self.payType) {
            case SYPayType_card:
                title = @"银联充值";
                break;
            case SYPayType_jd:
                title = @"京东充值";
                break;
            case SYPayType_qq:
                title = @"QQ充值";
                break;
                
            default:
                break;
        }
        topView.title = title;
        [topView setBackBlock:^(BOOL isSelected) {
            [weself.navigationController popViewControllerAnimated:YES];
        }];
        [self.view addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(170) + 24));
            }else{
                make.height.equalTo(@(rate750(170)));
            }
        }];
        _topView = topView;
    }
    return _topView;
}
//添加输入框
-(void)addTextField
{
    [self accountContentView];
    [self accountLabel];
    [self accountTextField];
}

/////********充值按钮*******///////
-(YDRechargeWithdrawalButtonView *)buttonView
{
    if (_buttonView == nil) {
        YDRechargeWithdrawalButtonView *buttonView = [YDRechargeWithdrawalButtonView rechargeWithdrawalButtonWithButtonTitle:@"充值"];
        buttonView.delegate = self;
        [self.view addSubview:buttonView];
        
        [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(63)));
            }else{
                make.height.equalTo(@(rate750(50)));
            }
        }];
        _buttonView = buttonView;
    }
    return _buttonView;
}

///*********accountContentView*******///////
-(UIView *)accountContentView
{
    if (_accountContentView == nil) {
        UIView *accountContentView = [[UIView alloc] init];
        [self.view addSubview:accountContentView];
        accountContentView.backgroundColor = [UIColor whiteColor];
        accountContentView.userInteractionEnabled = YES;
        [accountContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            if (isPhoneX) {
                make.top.equalTo(self.topView.mas_bottom).offset(rateX812(10));
                make.height.equalTo(@(rateX812(50)));
            }else{
                make.top.equalTo(self.topView.mas_bottom).offset(rate750(10));
                make.height.equalTo(@(rate750(50)));
            }
        }];
        _accountContentView = accountContentView;
    }
    return _accountContentView;
}
//金额label
-(UILabel *)accountLabel
{
    if (_accountLabel == nil) {
        UILabel *accountLabel = [[UILabel alloc] init];
        [self.accountContentView addSubview:accountLabel];//104 114 132
        accountLabel.textColor = NumberColor(104, 114, 132);
        accountLabel.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        accountLabel.text = @"金额";
        accountLabel.textAlignment = NSTextAlignmentCenter;
        [accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.accountContentView);
            make.left.equalTo(self.accountContentView);
            make.width.equalTo(@(rate375(61)));
        }];
        _accountLabel = accountLabel;
    }
    return _accountLabel;
}
-(OttoTextField *)accountTextField
{
    if (_accountTextField == nil) {
        OttoTextField *accountTextField = [[OttoTextField alloc] init];
        [self.accountContentView addSubview:accountTextField];
        accountTextField.textColor = [UIColor blackColor];
        accountTextField.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        accountTextField.placeholder = @"请输入充值金额";
        accountTextField.backgroundColor = [UIColor clearColor];
        accountTextField.borderStyle = UITextBorderStyleNone;
        accountTextField.textAlignment = NSTextAlignmentLeft;
        accountTextField.keyboardType = UIKeyboardTypeNumberPad;
        [accountTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        accountTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        
        
        [accountTextField setKeyboardType:KeyboardTypeNumber];
        [accountTextField setNumberKeyboardType:NumberKeyboardTypeNumber];
        accountTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        accountTextField.textFieldClickReturnDelegate = self;
        
        
        accountTextField.returnKeyType =UIReturnKeyDone;
        [accountTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
        [accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.accountContentView);
            make.left.equalTo(self.accountLabel.mas_right);
            make.right.equalTo(self.accountContentView.mas_right).offset(-rate375(16));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(20)));
            }else{
                make.height.equalTo(@(rate750(20)));
            }
        }];
        accountTextField.tintColor = [UIColor blackColor];
        accountTextField.delegate = self;
        
        _accountTextField = accountTextField;
    }
    return _accountTextField;
}
//tableView
-(UITableView *)tableView
{
    if (_tableView == nil) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [self.view addSubview:tableView];
        tableView.backgroundColor = NumberColor(247, 247, 247);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        //        tableView.scrollEnabled = NO;
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(self.accountContentView.mas_bottom).offset(isPhoneX ? rateX812(12) : rate750(12));
            
        }];
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}


- (NSMutableArray *)dataList
{
    if (!_dataList) {
        _dataList = [NSMutableArray arrayWithCapacity:2];
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithDictionary:@{@"title" : @"银行卡",
                                                                                    @"isSelected" : @1}];
        NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithDictionary:@{@"title" : @"支付宝",
                                                                                    @"isSelected" : @0}];
        
        
        [_dataList addObject:dic1];
        [_dataList addObject:dic2];
        
        
        
    }
    return _dataList;
}
@end
